package com.cc.util;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author CC
 * @version 1.0
 * @description: 文件上传工具类
 * @date 2025/4/21 14:54
 */
public class FileUtil {
    private static final Logger logger = Logger.getLogger(FileUtil.class);

    // 配置化的上传路径虚拟路径
    private static final String UPLOAD_PATH = "/upload";
    // 配置化的上传路径前缀，使用绝对路径
    private static final String UPLOAD_PATH_PREFIX = "D:\\IntelliJ IDEA 2023.3.8\\IdeaProjects\\Maven项目\\empsys\\upload";

    public static String getImgUrl(HttpServletRequest request, Part part) {
        try {
            // 获取文件名
            String fileName = part.getSubmittedFileName();
            if (fileName == null || fileName.isEmpty()) {
                throw new IllegalArgumentException("文件名为空");
            }

//            // 指定上传路径
//            String realPath = request.getServletContext().getRealPath(UPLOAD_PATH_PREFIX);
//            if (realPath == null) {
//                throw new IllegalStateException("无法获取上传路径");
//            }

            // 校验路径安全性，防止路径遍历攻击
            File uploadDir = new File(UPLOAD_PATH_PREFIX);
            if(!uploadDir.exists()) {
                // 如果上传目录不存在，则创建它
                uploadDir.mkdirs();
            }

            // 重命名文件以避免冲突
            String uniqueFileName = UUID.randomUUID().toString() + "_" + fileName;
            File uploadedFile = new File(uploadDir, uniqueFileName);

            // 将文件上传到服务器
            part.write(uploadedFile.getAbsolutePath());

            logger.debug("文件上传成功："+ UPLOAD_PATH_PREFIX + "/" + uniqueFileName);
            // 返回文件的访问路径
            return UPLOAD_PATH + "/" + uniqueFileName;

        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }
}

